#ifndef TSERIALIZE_H
#define TSERIALIZE_H
#include <iostream>
#include <QString>
#include <QDateTime>
#include <QIODevice>
#include <QDataStream>

class TSerialize  //序列化与反序列化数据
{
public:
    static QString getTimestamp()//获取时间戳 QString格式
    {
        return QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch());
    }

    template<typename T>// 基础模板，用于递归终止
    static void writeToByteArray(QDataStream& dataStream, T&& arg)
    {
        dataStream << std::forward<T>(arg);
    }

    template<typename T, typename... Args>// 递归模板，用于处理多个参数
    static void writeToByteArray(QDataStream& dataStream, T&& first, Args&&... args)
    {
        dataStream << std::forward<T>(first);
        if (sizeof...(args) > 0)writeToByteArray(dataStream, std::forward<Args>(args)...);
    }

    template<typename... Args>// 封装函数，便于调用
    static QByteArray serialize(Args&&... args)
    {
        QByteArray byteArrData;
        QDataStream dataStreamData(&byteArrData, QIODevice::WriteOnly);
        writeToByteArray(dataStreamData, std::forward<Args>(args)...);
        QByteArray byteArrLen;
        QDataStream dataStreamLen(&byteArrLen, QIODevice::WriteOnly);
        dataStreamLen << byteArrData.size() + 8;
        return byteArrLen + byteArrData;
    }
};

#endif // TSERIALIZE_H
